<template>
  <div class="page">
    <div class="container">
      <div class="search-group">
      </div>
      <div class="table-web table-container">
        <!-- v-loading="loading" -->
        <el-table
          ref="table"
          :data="tableData"
          row-key="id"
          lazy
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          :highlight-current-row="true"
          style="width: 100%"
          :header-cell-style="{
            background: '#F4F9FF',
            color: '#087CD6',
            fontSize:'14px'
          }"
        >
          <el-table-column
            show-overflow-tooltip
            prop="orgName"
            label="机构名称"
            align="left"
          />
          <el-table-column
          show-overflow-tooltip
            prop="orgCode"
            label="机构编码"
            align="left"
          />

          <el-table-column
          show-overflow-tooltip
            prop="areaName"
            label="地区"
            align="left"
          />
          <el-table-column
          show-overflow-tooltip
            prop="status"
            label="状态"
            align="left"
            width="150"
          >
            <template #default="scope">
              <el-switch
                v-if="scope.row.level >= 1"
                :before-change="beforeChangeColumn"
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeStatus(scope.row)"
              />
              <span v-else></span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            width="250"
            header-align="center"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.level >= 1 && scope.row.level < 6"
                type="primary"
                class="btn-row-add"
                plain
                header-align="center"
                @click="addchildren(scope.row)"
              >
                添加
              </el-button>
              <el-button
                v-if="scope.row.level >= 1"
                class="btn-row-edit"
                type="success"
                plain
                header-align="center"
                @click="edit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.level >= 1 && scope.row.level <= 4"
                type="primary"
                class="btn-row-other"
                plain
                header-align="center"
                @click="generate(scope.row, 1)"
              >
                生成内部机构
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--新增/编辑表单-->
    <pub-dialog
      v-if="dialogFormVisible"
      :title="strtitle"
      v-model:visible="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="45%"
    >
      <dialogEdit
        :id="editId"
        ref="ruleForm"
        :is-edit="isEdit"
        :parent-id="parentId"
        :parent-info="parentInfo"
        v-model:btn-loading="btnLoading"
        @close="close"
        @submitForm="submitForm"
      />
    </pub-dialog>
  </div>
</template>

<script>
export default {
  name: 'government'
}
</script>
<script setup>
import dialogEdit from './create.vue'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {
  addOrganization,
  updateOrganization,
  getOrganizationInfo,
  addChildrenOrganization,
  updateOrganizationStatus,
  getChildrenOrganizationList
} from '@/api/system'

import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Plus
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const dialogFormVisible = ref(false)
const showOperatorDialog = ref(false)
const btnLoading = ref(false)
const isEdit = ref(true)
const loading = ref(true)
const editId = ref('')
const parentId = ref('')
const parentInfo = ref({})
const parentString = ref('')
const strtitle = ref('')
const search = ref('')
const tableData = ref([])
const searchForm = reactive({})
const page = reactive({})
const lazyData = ref([])
const total = ref(0)
const switchState = ref(false)

onMounted(() => {
  getlist()
  window['reload'] = () => {
    getlist()
  }
})

const beforeChangeColumn = () => {
  switchState.value = true
  return switchState.value
}

const changeStatus = row => {
  if (switchState.value) {
    const params = {
      id: row.id,
      status: row.status
    }
    updateOrganizationStatus(params).then(result => {
      if (result.succeed) {
        getlist(0)
        ElMessage({
          type: 'success',
          message: '修改成功'
        })
      }
    })
  }
}

const load = async (tree, treeNode, resolve) => {
  const id = tree.id
  const array = await getlist(id)
  console.log('array', array)
  resolve(array)
}

const getlist = async (pId = 0) => {
  try {
    loading.value = true
    const result = await getChildrenOrganizationList({ pId })
    if (result.succeed) {
      const array = []
      if (result.data && result.data.length > 0) {
        if (pId === 0) {
          tableData.value = []
          result.data.forEach(item => {
            tableData.value.push({
              ...item,
              hasChildren: true
            })
          })
        } else {
          result.data.forEach(item => {
            array.push({
              ...item,
              hasChildren: true
            })
          })
        }
      }
      loading.value = false
      return array
    }
  } catch (error) {
    console.log('error', error)
  }
}

const handleSizeChange = val => {
  page.pageSize = val
  getlist()
}

const handleCurrentChange = val => {
  page.pageNum = val
  getlist()
}

const getStateName = (row, columu) => {
  if (row.status == 1) {
    return '启用'
  } else {
    return '停用'
  }
}

const getparentName = (tree = [], id) => {
  let parentName = []
  let find = false
  tree.map(item => {
    if (!find) {
      if (id == item.id) {
        find = true
        parentName = item.orgName
        return false
      } else {
        if (item.children.length > 0) {
          parentName += getparentName(item.children, id)
        }
      }
    }
  })
  return parentName
}

const addchildren = row => {
  strtitle.value = '新增机构'
  isEdit.value = false
  parentId.value = row.id
  parentInfo.value = row
  dialogFormVisible.value = true
}

const edit = row => {
  strtitle.value = '编辑机构'
  parentId.value = row.id
  parentInfo.value = {}
  editId.value = row.id
  isEdit.value = true
  dialogFormVisible.value = true
}

const enable = row => {
  ElMessageBox.confirm('是否要启用此机构吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      API.enableOrg({
        id: row.id,
        orgCode: row.orgCode,
        status: 1
      }).then(result => {
        ElMessage({
          message: result.msg,
          type: result.succeed == true ? 'success' : 'warning'
        })
        getlist()
      })
    })
    .catch(() => {})
}

const disable = row => {
  ElMessageBox.confirm('是否要禁用此机构吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      API.disable({
        id: row.id,
        orgCode: row.orgCode,
        status: 0
      }).then(result => {
        ElMessage({
          message: result.msg,
          type: result.succeed == true ? 'success' : 'warning'
        })
        getlist()
      })
    })
    .catch(() => {})
}

const generate = row => {
  ElMessageBox.confirm('是否要生成下属机构?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      addChildrenOrganization(row.id).then(result => {
        ElMessage({
          message: result.msg,
          type: result.succeed == true ? 'success' : 'warning'
        })
        if (result.succeed) getlist()
      })
    })
    .catch(() => {})
}

const submitForm = data => {
  console.log('data', data, 11111)
  btnLoading.value = true
  const urlHandle = isEdit.value ? updateOrganization : addOrganization
  urlHandle(data).then(result => {
    btnLoading.value = false
    if (result.succeed) {
      tableData.value = []
      ElMessage({
        message: result.msg,
        type: 'success'
      })
      getlist()
      close()
      dialogFormVisible.value = false
      isEdit.value = false
    }
  })
}

const submitTheForm = data => {
  API.changeOperator(data).then(result => {
    if (result.succeed) {
      ElMessage({
        message: result.msg,
        type: 'success'
      })
      getlist()
      showOperatorDialog.value = false
    }
  })
}

const close = () => {
  dialogFormVisible.value = false
  showOperatorDialog.value = false
}

const perfect = row => {
  router.push({
    path: '/system/orgmanage/perfect',
    query: {
      id: row.id
    }
  })
}

const del = row => {
  ElMessageBox.confirm('确认删除选择的记录？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      API.deleteOrg({
        id: row.id
      }).then(result => {
        ElMessage({
          message: result.msg,
          type: result.succeed == true ? 'success' : 'warning'
        })
        if (result.succeed) getlist()
      })
    })
    .catch(() => {})
}

/* const changeOperator = row => {
  editId.value = row.id
  showOperatorDialog.value = true
} */
</script>

<style lang="scss" scoped>
// .search-btn {
//   margin-bottom: 10px;
//   margin-left: 10px;
// }

// .search-form {
//   justify-content: flex-end;
// }
.el-table--fit {
  overflow: auto;
}

.table-web {
  font-family: 'Microsoft YaHei';
  .el-table td.el-table__cell,
  .el-table th.el-table__cell.is-leaf {
    border-bottom: 0px !important;
  }
  :deep(.el-button) {
    border: 0 solid transparent !important;
    background-color: transparent !important;
    font-size: 14px !important;
    padding: 6px 0px !important;
    font-family: 'Microsoft YaHei';
  }
  :deep(.el-button + .el-button) {
    margin-left: 19px !important;
  }
  :deep(.el-button--success) {
    // color: var(--el-color-success) !important;
    // &:hover {
    //   color: var(--el-color-success) !important;
    // }

    color: #087cd6 !important;
    &:hover {
      color: #087cd6 !important;
    }
  }
  :deep(.el-button--primary) {
    color: #087cd6 !important;
    &:hover {
      color: #087cd6 !important;
    }
  }
  :deep(.el-button--danger) {
    // color: var(--el-color-danger) !important;
    // &:hover {
    //   color: var(--el-color-danger) !important;
    // }
    color: #087cd6 !important;
    &:hover {
      color: #087cd6 !important;
    }
  }
}
</style>
